const tools = require('../common/tools');
const dbUtil = require('../model/dbUtil');
const config = require('../config');
const dateFormat = require('dateformat');

//用户登录
function doLogin(req, res) {
    let { user_name, user_pwd } = req.body;
    let sql = '';
    if (Number(user_name) && Number(user_name) == 11) {
        sql = "select * from users where user_phone=? and user_pwd=?";
    } else {
        sql = "select * from users where user_name=? and user_pwd=?";
    }
    let parsms = [user_name, user_pwd];
    console.log(parsms);
    dbUtil.query(sql, parsms, (err, results) => {
        if (err) {
            console.log(err.message);
            res.render('error', { error: "服务器出错 404..." });
        } else {
            if (results.length > 0) {
                if (results[0].user_state == "Y" && results[0].user_role == "normal") {
                    req.session.currentUser = { uname: results[0].user_name, uid: results[0].user_id, userRole: results[0].user_role };
                    let data = {
                        code: 200,
                        username: user_name,
                        message: '登陆成功',
                        href: '/'
                    }
                    res.send(data);

                } else {
                    let data = {
                        code: 400,
                        message: '账号已被禁用',
                    }
                    res.send(data);
                }
            } else {
                let data = {
                    code: 400,
                    message: '账号或密码错误',
                }
                res.send(data);
            }
        }
    });
}


//用户注册
async function doRegister(req, res) {
    let { user_name, user_pwd, suc_pwd, user_phone } = req.body;
    // console.log(user_name, user_pwd, suc_pwd);
    let flag = await userExist(user_name);
    //console.log(flag);
    //用户存在
    if (flag) {
        let data = {
            code: 300,
            message: '用户已被注册'
        }
        res.send(data);
    } else {
        //生成用户昵称
        let user_nickname = '用户' + String(Date.now()).substr(6, );
        let sql = ` begin;
                    insert into users(user_nickname,user_name,user_pwd,user_phone) values(?,?,?,?);
                    insert into user_wallet set user_id=(select user_id from users where user_name=?);
                    commit;
                    rollback;
                    `;
        let params = [user_nickname, user_name, user_pwd, user_phone, user_name];

        if (user_pwd.trim() == suc_pwd.trim()) {
            dbUtil.query(sql, params, async(err, result) => {
                if (err) {
                    console.log(err.message);
                    res.render('error', { error: "服务器出错 404..." });
                    //res.send({ code: 404, message: "服务器出错 404..." });
                } else {
                    if (result) {
                        let data = {
                            code: 200,
                            message: "注册成功",
                            href: '/login',
                            userInfo: user_name
                        }
                        console.log(data);
                        res.send(data);
                    } else {
                        let data = {
                            code: 400,
                            message: "注册失败",
                        }
                        console.log(data);
                        res.send(data);
                    }
                }
            })
        } else {
            let data = {
                code: 400,
                message: '账号或密码错误，注册失败'
            }
            res.send(data);
        }
    }
}

//私有方法 判断用户是否已被注册
function userExist(username) {
    return new Promise((resolve, reject) => {
        let sql = "select * from users where user_name=?";
        let params = [username];
        dbUtil.query(sql, params, (err, result) => {
            if (err) {
                reject(err.message);
            } else {
                if (result.length > 0) {
                    resolve(true); //用户存在
                } else {
                    resolve(false); //用户不存在
                }
            }
        })
    });
}


//用户个人中心 
// 个人资料
function userMessage(req, res) {
    let { uid } = req.session.currentUser;
    let sql = "select * from users where user_id=?";
    let params = [uid];
    dbUtil.query(sql, params, (err, result) => {
        if (err) {
            console.log(err.message)
        } else {
            if (result.length > 0) {
                //console.log(result);
                res.render('user-admin/user-message', { userInfo: result[0] });
            } else {
                res.render('user-admin/user-message', {});
            }
        }
    })
}

//用户个人资料修改
async function updateUserMsg(req, res) {
    let { uid } = req.session.currentUser;
    let { user_nickname, user_sex, user_phone, user_email } = req.body;
    console.log(uid, user_nickname, user_sex, user_phone, user_email);

    let sql = "update users set user_nickname=?,user_sex=?,user_phone=?,user_email=? where user_id=?";
    let params = [user_nickname, user_sex, user_phone, user_email, uid];

    let result = await dbUtil.asyncQuery(sql, params);
    //console.log(result);
    if (result.protocol41) {
        let data = {
            code: 200,
            message: '信息修改成功',
            color: '#1e1e1e'
        };
        // console.log(data);
        res.send(data);
    } else {
        let data = {
            code: 400,
            message: '信息修改失败！',
            color: '#f56c6c'
        };
        // console.log(data);
        res.send(data);
    }
}

//用户个人资料 头像 修改
async function upLogoFile(req, res) {
    let { uid } = req.session.currentUser;
    let filePath = ''; //用于保存图片地址
    let sql = "update users set user_logo=? where user_id=?";
    let params = [];
    //更新 头像
    //判断是否上传头像文件
    if (req.file) {
        filePath = req.file.path.split('public')[1]; // 打印 \uploads\20201113\1605261036242.jpg
        params = [filePath, uid];
    } else {
        return;
    }

    let result = await dbUtil.asyncQuery(sql, params);
    //console.log(result);
    if (result.protocol41) {
        let data = {
            code: 200,
            message: '头像修改成功',
            color: '#1e1e1e'
        }
        console.log(data);
        res.send(data);
    } else {
        let data = {
            code: 400,
            message: '头像修改失败',
            color: '#f56c6c'
        }
        console.log(data);
        res.send(data);
    }
}


//用户订单页
async function userOrder(req, res) {
    let action = "myOrder";
    let { uid } = req.session.currentUser;
    let { cartPage } = req.query;

    let count = 0, //数据总条数
        // 接收客户端传递过来的当前页参数
        page = cartPage || 1; //默认第一页

    let sql = "select * from user_order_list where user_id=?";
    let params = [uid];
    let result = await dbUtil.asyncQuery(sql, params);
    count = result.length;
    // console.log(count);

    //统计 待付款 待收货。。。信息
    let statData = {
        order_status: 0,
        order_take: 0,
        order_deliver: 0,
        order_comment: 0
    }
    result.forEach((item) => {
        if (item.order_status != 'T') { //待付款
            statData.order_status += 1;
        }
        if (item.order_take != 'T' && item.order_status == "T" && item.order_deliver == 'T') { //待收货
            statData.order_take += 1;
        }
        if (item.order_deliver != 'T' && item.order_status == "T") { //待发货
            statData.order_deliver += 1;
        }

        if (item.order_comment == '0' && item.order_status == "T" && item.order_take == "T") { //待评价
            statData.order_comment += 1;
        }
    });
    // console.log(statData);

    // 每一页显示的数据条数
    let pageSize = 10;
    // 总页数
    let total = Math.ceil(count / pageSize);
    // 页码对应的数据查询开始位置
    let start = (page - 1) * pageSize;

    //客户端展示的页码数
    let getPage = tools.layPage(page, 5, total);
    // console.log(getPage);

    sql = `select gd.g_show_img,gd.g_name,gd.g_desc,ol.* from goods gd,user_order_list ol
                where gd.g_id = ol.g_id
                and  user_id=? ORDER BY order_id DESC limit ?,?`;
    params = [uid, start, pageSize];
    let data = await dbUtil.asyncQuery(sql, params);
    // console.log("我的订单：————————————↓↓↓↓↓↓↓↓↓");
    // console.log(data);
    res.render('user-admin/user-order', {
        statData,
        order_list: data,
        action,
        page,
        total,
        getPage
    });
}


//用户购物车渲染
async function doShowCart(req, res) {
    let action = "myCart"; //选项标识
    let { uid } = req.session.currentUser;

    let count = 0, //数据总条数
        // 接收客户端传递过来的当前页参数
        page = req.query.cartPage || 1; //默认第一页

    {
        let sql = "select count(*) as total from user_cart where user_id=?";
        let params = [uid];
        count = await dbUtil.asyncQuery(sql, params);
        count = count[0].total;
        // console.log(count);
    }

    // 每一页显示的数据条数
    let pageSize = config.pageSize;
    // 总页数
    let total = Math.ceil(count / pageSize);
    // 页码对应的数据查询开始位置
    let start = (page - 1) * pageSize;

    //客户端展示的页码数
    let getPage = tools.layPage(page, 5, total);
    // console.log(getPage);

    let sql = `select * from goods g,user_cart c
                    where g.g_id=c.g_id 
                    and user_id=? ORDER BY cart_id DESC limit ?,?`;
    let params = [uid, start, pageSize];
    let result = await dbUtil.asyncQuery(sql, params);
    // console.log(result);
    res.render('user-admin/user-cart', {
        data: result,
        action,
        page,
        total,
        getPage
    });
}


//用户购物车商品删除功能
async function doUserCartDel(req, res) {
    let { uid } = req.session.currentUser;
    let { cart_id } = req.body;
    let sql = "delete from user_cart where cart_id=? and user_id=?";
    let params = [cart_id, uid];
    let result = await dbUtil.asyncQuery(sql, params);
    console.log(result);
    if (result) {
        res.send({
            code: 200,
            message: '删除成功',
            color: '#1e1e1e'
        });
    } else {
        res.send({
            code: 400,
            message: '信息修改失败！',
            color: '#f56c6c'
        });
    }
}

//用户购物车商品数量修改功能
async function doUserCartUpdate(req, res) {
    let { uid } = req.session.currentUser;
    let { g_count, cart_id } = req.body;
    // console.log(g_count, cart_id);
    let sql = "update user_cart set g_count=? where cart_id=? and user_id=?";
    let params = [g_count, cart_id, uid];
    let result = await dbUtil.asyncQuery(sql, params);
    if (result) {
        res.send({ code: 200, message: "数量修改成功" }); //更新成功结束响应
    } else {
        res.send({ code: 400, message: "数量修改失败" });
    }
}

//提交订单页面
async function subOrderPage(req, res) {
    let { uid } = req.session.currentUser;

    //商品数据
    let { g_id, g_count, g_attr } = req.query
    let sql = `select * from goods where g_id=?`;
    let params = [g_id]
    let result = await dbUtil.asyncQuery(sql, params);
    // console.log(result);

    // 收货地址数据
    let addInfo = null;
    if (result.length > 0) {
        sql = `select * from user_address where user_id=?`;
        params = [uid];
        addInfo = await dbUtil.asyncQuery(sql, params);

        //处理  将字符串地址 转化成 数组
        for (var i = 0; i < addInfo.length; i++) {
            var arr = addInfo[i].add_info.split("&");
            addInfo[i].add_info = {};
            for (var j = 0; j < arr.length; j++) {
                addInfo[i].add_info['p' + (j + 1)] = arr[j];
            }
        }
        // console.log(addInfo);
        res.render('sub-order', { goodInfo: result[0], addInfo: addInfo, g_id, g_count, g_attr });
    }
}

//添加 & 修改 收货地址
async function doSetAddress(req, res) {
    let { uid } = req.session.currentUser;
    //获取页面来的数据 
    let { add_info, add_id } = req.query;
    if (add_id) {
        //更新地址
        let sql = `update user_address set add_info=? where user_id=? and add_id=?`;
        let params = [add_info, uid, add_id];
        let result = await dbUtil.asyncQuery(sql, params);
        if (result) {
            let data = {
                code: 200,
                message: "地址修改成功"
            }
            console.log(data);
            res.send(data);
        } else {
            let data = {
                code: 400,
                message: "地址修改失败"
            }
            console.log(data);
            res.send(data);
        }
    } else {
        // 需求： 用户的收货地址个数不能超过 4 个
        //添加地址
        let sql = "select count(*) as addcount from user_address where user_id=?";
        let params = [uid];
        //获取用户地址已有 的 数量
        let result = await dbUtil.asyncQuery(sql, params);
        result = result[0].addcount
        console.log("地址数量", result);

        if (result >= 4) {
            let data = {
                code: 400,
                message: "收货地址数量最多 4 个,请修改旧地址"
            }
            console.log(data);
            res.send(data);
        } else {

            sql = `update user_address set normal='N' where user_id=?;
                insert into user_address(add_id,user_id,add_info,normal) 
                values(null,?,?,?)
                `;
            params = [uid, uid, add_info, 'Y'];
            let rs = await dbUtil.asyncQuery(sql, params);

            console.log("rs------↓↓↓");
            console.log(rs);

            if (rs) {
                let insertId = rs[1].insertId; //回去sql 语句 结果中的id
                let data = {
                    code: 200,
                    insertId,
                    message: "新增地址成功"
                }
                console.log(data);
                res.send(data);
            } else {
                let data = {
                    code: 400,
                    message: "新增地址失败"
                }
                console.log(data);
                res.send(data);
            }
        }

    }
}

//提交订单操作 
async function doOrder(req, res) {
    //用户ID
    let { uid } = req.session.currentUser;
    //前端需要传递的数据 商品id 和 数量
    let { g_id, order_count, add_id, order_attr } = req.body;
    // console.log(g_id, order_count, add_id, order_attr);

    if (!add_id) {
        let data = {
            code: 400,
            message: "您还没收货地址",
        }
        console.log(data);
        res.send(data);
        return;
    }

    //获取商品库存数量
    let gNum = await getGoodNum(g_id)
    if (gNum < order_count) {
        let data = {
            code: 400,
            message: '库存不足，提交订单失败',
        }
        res.send(data);
        return;
    }

    //查询商品价格
    let sql = "select g_price from goods where g_id=?";
    let params = [g_id];
    let price = await dbUtil.asyncQuery(sql, params);
    price = price[0].g_price; //商品价格
    //总价
    let totalPrice = price * order_count;
    // console.log("总价" + totalPrice);
    if (!price) {
        let data = {
            code: 400,
            message: "订单提交失败",
        }
        console.log(data);
        res.send(data);
        return;
    }

    //数据库取出 收货地址 add_info
    sql = "select add_info from user_address where add_id=? and user_id=?";
    params = [add_id, uid];
    let addInfo = await dbUtil.asyncQuery(sql, params);
    addInfo = addInfo[0].add_info;
    // console.log(addInfo);
    if (!addInfo) {
        let data = {
            code: 400,
            message: "您还没收货地址",
        }
        console.log(data);
        res.send(data);
        return;
    }

    //订单编号
    let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
    let randomNum = String(Math.random()).split(".")[1].charAt(1);
    let orderCode = arr[randomNum] + Date.now() + String(uid); //订单编号
    console.log('订单编号:' + orderCode);


    sql = `insert into user_order_list(order_id,order_num,user_id,order_attr,g_id,order_price,order_count,order_total,order_address)
                values(null,?,?,?,?,?,?,?,?)`;
    params = [orderCode, uid, order_attr, g_id, price, order_count, totalPrice, addInfo];
    // console.log(params);

    let result = await dbUtil.asyncQuery(sql, params);
    if (result) {
        let data = {
            code: 200,
            message: "订单提交成功",
            href: '/user/dzyp-pay?orderCode=' + orderCode
        }
        console.log(data);
        res.send(data);
    } else {
        let data = {
            code: 400,
            message: "订单提交失败",
        }
        console.log(data);
        res.send(data);
    }

}


//判断商品库存表的库存数量 是否 大于提交的订单数 
//返回值： 库存数量
async function getGoodNum(g_id) {
    let sql = 'select * from good_count where g_id=?';
    let params = [g_id];
    let rs = await dbUtil.asyncQuery(sql, params);
    if (rs.length > 0) {
        return rs[0].g_num;
    } else {
        return new Error('');
    }
}


//支付页面
async function dzypPayPage(req, res) {
    let { uid, uname } = req.session.currentUser;
    let { orderCode } = req.query; //获取订单编号

    let sql = `select * from user_order_list where order_num=? and user_id=?`;
    let params = [orderCode, uid];
    let result = await dbUtil.asyncQuery(sql, params);
    if (!result.length > 0) {
        res.render('error', { message: "订单不存在！" });
        return;
    };
    console.log("------------------>>>>>>>>>>>>>>>");
    console.log("订单信息: ↓↓↓");
    console.log(result[0]);
    res.render('dzyp-pay', { uname, orderInfo: result[0] });
}

//支付操作
async function doPayHandle(req, res) {
    let { uid } = req.session.currentUser;
    //获取订单编号 和 支付密码
    let { orderCode, pay_key } = req.body;
    console.log("------------------>>>>>>>>>>>>>>>");
    console.log("支付操作：订单号----->" + orderCode);

    //如果没有设置钱包密码 或 密码为空 将不允许提交订单
    let isPayKey = await isUserWalletPwd(uid);
    if (!isPayKey) {
        let data = {
            code: 400,
            message: '没有设置支付密码，<a href="/user/wallet">去设置</a>',
        }
        res.send(data);
        return;
    }

    //查询当前订单的需要支付的总金额
    let sql = `select * from user_order_list where order_num=? and user_id=?`;
    let params = [orderCode, uid];
    let rs = await dbUtil.asyncQuery(sql, params);
    let g_id = rs[0].g_id; //商品id
    let countNum = rs[0].order_count; //订单数量
    let totalPrice = rs[0].order_total; //要付款的金额
    console.log("支付金额:" + totalPrice);

    //获取商品库存数量  //如果库存不足将不能支付
    let gNum = await getGoodNum(g_id)
    if (gNum < countNum) {
        let data = {
            code: 400,
            message: '库存不足，支付失败',
        }
        data.href = `/user/pay-status?orderCode=${orderCode}&message=${data.message}&code=${data.code}`;
        res.send(data);
        return;
    }

    if (totalPrice) {
        //查询当前用户钱包余额是否够支付当前商品的价格
        sql = "select money from user_wallet where user_id=?";
        params = [uid];
        let myMoney = await dbUtil.asyncQuery(sql, params);
        myMoney = myMoney[0].money; //用户余额
        console.log("用户余额：", myMoney);

        if (myMoney < totalPrice) {
            let data = {
                code: 400,
                message: "账户余额不足，支付失败"
            }
            data.href = `/user/pay-status?orderCode=${orderCode}&message=${data.message}&code=${data.code}`;
            console.log(data);
            res.send(data);
            return;
        }

        //如果订单已经支付 就跳过支付
        let flag = await currentOrderPayStatus(uid, orderCode);
        if (flag.order_status == 'T') {
            let data = {
                code: 200,
                message: "订单已支付,无需重复支付"
            };
            data.href = `/user/pay-status?orderCode=${orderCode}&message=${data.message}`;
            console.log(data);
            res.send(data);
            return;
        }


        //事务处理
        sql = `begin;
                update user_wallet set money=money-? where user_id=? and pay_key=?;
                update user_wallet set money=money+? where user_id=${config.adminId};  
                update user_order_list set order_status='T' where user_id=? and order_num=?;
                update good_count set g_num=g_num-${countNum},g_sales=g_sales+${countNum} where g_id=?;
                
                commit;
                rollback`;
        params = [totalPrice, uid, pay_key, totalPrice, uid, orderCode, g_id];

        let result = await dbUtil.asyncQuery(sql, params);
        result && console.log("事务执行成功");

        if (result.length > 0) {
            //支付成功 将修改库存表
            let data = {
                code: 200,
                message: "订单支付成功"
            };
            data.href = `/user/pay-status?orderCode=${orderCode}&message=${data.message}`;
            console.log(data);
            res.send(data);
        } else {
            let data = {
                code: 400,
                message: "支付失败"
            }
            data.href = `/user/pay-status?orderCode=${orderCode}&message=${data.message}&code=${data.code}`;
            console.log(data);
            res.send(data);
        }

    }
}

//私有方法 判断用户钱包 是否设置密码
function isUserWalletPwd(userId) {
    let sql = "select pay_key from user_wallet where user_id=?";
    let params = [userId];
    return new Promise((resolve, reject) => {
        dbUtil.query(sql, params, (err, result) => {
            if (err) {
                reject(err.message);
            } else {
                if (result.length > 0 && result[0].pay_key) {
                    resolve(true); //设置了密码
                } else {
                    resolve(false); //没有设置密码
                }
            }
        })
    })
}



//判断当前订单是否已经支付过了
async function currentOrderPayStatus(uid, orderCode) {
    let sql = "select order_status from user_order_list where user_id=? and order_num=?";
    let params = [uid, orderCode];
    let result = await dbUtil.asyncQuery(sql, params);
    return result[0];
}

//支付状态页面 
async function payStatusPage(req, res) {
    let { uid } = req.session.currentUser;
    let { message, orderCode } = req.query;

    let sql = "select * from user_order_list where user_id=? and order_num=?";
    let params = [uid, orderCode];
    let result = await dbUtil.asyncQuery(sql, params);
    //处理 收货地址信息
    result[0].order_address = result[0].order_address.split('&').join("&nbsp;");

    let g_id = result[0].g_id; //商品id
    let orderStatus = result[0].order_status; //订单状态

    let goodInfo = "";
    if (result.length > 0) {
        //查询当前商品的图片 用于页面展示
        sql = "select g_name,g_desc,g_show_img from goods where g_id=?";
        params = [g_id];
        goodInfo = await dbUtil.asyncQuery(sql, params);
        goodInfo = goodInfo[0]

        if (orderStatus == "T") {
            //成功
            res.render('pay-status', {
                message: message || "订单已支付",
                goodInfo,
                orderInfo: result[0],
                dateFormat
            })
            return;
        }
        if (req.query.code && req.query.code == 400 || orderStatus == "F") {
            //支付失败 
            res.render('pay-status', {
                orderStatus,
                message: message || "待支付",
                goodInfo,
                orderInfo: result[0],
                dateFormat
            });
        }
    }
}

//取消订单(未付款的订单)
async function delOrder(req, res) {
    let { uid } = req.session.currentUser;
    //获取前台数据
    let { orderNum } = req.query;

    console.log(uid, orderNum);

    let sql = "delete from user_order_list where order_num=? and user_id=?";
    let params = [orderNum, uid];
    let result = await dbUtil.asyncQuery(sql, params);

    if (result) {
        let data = {
            code: 200,
            message: "订单已取消",
            color: '#1e1e1e'
        }
        res.send(data)
    } else {
        let data = {
            code: 400,
            message: "订单取消失败",
            color: '#f56c6c',
            error: result
        }
        res.send(data)
    }
}


module.exports = {
    doLogin,
    doRegister,
    userMessage,
    userOrder,
    updateUserMsg,
    upLogoFile,
    doShowCart,
    doUserCartDel,
    doUserCartUpdate,
    dzypPayPage,
    subOrderPage,
    doSetAddress,
    doOrder,
    doPayHandle,
    payStatusPage,
    delOrder
}